Description:
Delphi.NET
provides the for in
construction for enumerating collection members
and allows the programmer to implement their own enumerators.
Usually, it is not possible to update a collection during enumeration.
For example, if you try to update System.Collection.ArrayList
inside of a for in
body, you will get an InvalidOperationException.
However, the programmer can implement their own enumerators and forget to
check that the collection was not updated. Code that updates a collection during
iteration can work in some cases, but in general, can cause unpredictable behavior.
This audit detects code that attempts to modify a collection inside of a for in
loop enumerating the
collection. Methods with names containing Delete, Remove, Insert, and Add
are considered to be mutators.
Incorrect:
var x:String;
begin
for x in c do
if x.Equals(name) then
c.Remove(x);
end;
Correct:
var x:String;
toBeRemoved:ArrayList;
begin
toBeRemoved := ArrayList.Create;
for x in c do
if x.Equals(name) then
toBeRemoved.Add(x);
for x in toBeRemoved do
c.Remove(x);
end;